Page({
    data: {
      url: '',
      result: "请上传图片并识别",
      tempFilePath: null,
      isRecognizing: false
    },
    
    afterRead(event) {
      const { file } = event.detail;
      const filePath = file.tempFilePath;
      
      this.setData({
        url: filePath,
        tempFilePath: filePath,
        result: "图片已上传，请点击开始识别"
      });
    },
    
    startIdentify() {
      const that = this;
      const filePath = this.data.tempFilePath;
      
      if (!filePath) {
        wx.showToast({
          title: '请先上传图片',
          icon: 'none'
        });
        return;
      }
      
      this.setData({
        isRecognizing: true,
        result: "识别中..."
      });
      
      wx.uploadFile({
        url: 'http://localhost:8080/textidentify/textidentify',
        filePath: filePath,
        name: 'file',
        success(res) {
          try {
            const data = JSON.parse(res.data);
            if (data.success && data.result) {
              that.setData({
                result: data.result
              });
            } else {
              that.setData({
                result: data.result || "识别失败"
              });
            }
          } catch (e) {
            that.setData({
              result: "解析结果出错"
            });
          }
        },
        fail(err) {
          that.setData({
            result: "请求失败: " + (err.errMsg || "")
          });
        },
        complete() {
          that.setData({
            isRecognizing: false
          });
        }
      });
    },
  
    onLoad() {
      wx.setNavigationBarTitle({
        title: "手写文字识别"
      });
    }
  });